package com.gh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gh.enums.PaymentTypeEnum;
import com.gh.enums.RefundStatusEnum;
import com.gh.exception.HospitalException;
import com.gh.model.order.OrderInfo;
import com.gh.model.order.PaymentInfo;
import com.gh.model.order.RefundInfo;
import com.gh.service.OrderService;
import com.gh.service.PaymentService;
import com.gh.service.RefundInfoService;
import com.gh.service.WeixinService;
import com.gh.utils.ConstantPropertiesUtils;
import com.gh.utils.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Eric
 * @Date 2021/6/28 20:37
 * @Version 1.0
 */
@Service
public class WeixinServiceImpl implements WeixinService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RefundInfoService refundInfoService;

    @Override
    public Map createNative(Long orderNo) {
        try {
            Map payMap = (Map) redisTemplate.opsForValue().get(orderNo.toString());
            if (payMap != null) {
                return payMap;
            }
            //1.根据订单号查询订单信息
            OrderInfo orderInfo = orderService.getById(orderNo);
            //2.向支付记录表添加信息
            paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
            //3.根据map设置二维码需要参数
            Map m = new HashMap();
            m.put("appid", ConstantPropertiesUtils.APPID);
            m.put("mch_id", ConstantPropertiesUtils.PARTNER); //商户号
            m.put("nonce_str", WXPayUtil.generateNonceStr()); //生成随机字符串
            m.put("body", orderInfo.getReserveDate() + "就诊" + orderInfo.getDepname()); //生成二维码的名字
            m.put("out_trade_no", orderInfo.getOutTradeNo()); //填写订单号
            //orderInfo.getAmount().multiply(new BigDecimal("100")).longValue() + ""
            m.put("total_fee", "1");//转换价格
            m.put("spbill_create_ip", "127.0.0.1"); //ip地址
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");//回调地址
            m.put("trade_type", "NATIVE"); //支付类型
            //4.发送httpclient请求，传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);//使https生效
            //执行请求发送
            client.post();
            //5.得到发送请求返回结果,返回内容是使用xml格式返回
            String xml = client.getContent();
            //把xml格式转换成map集合，把map集合返回
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //最终返回数据的封装
            Map map = new HashMap();
            map.put("orderId", orderNo);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));//返回二维码操作状态码
            map.put("codeUrl", resultMap.get("code_url"));//二维码地址
            if (resultMap.get("result_code") != null) {
                redisTemplate.opsForValue().set(orderNo.toString(), map, 120L, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new HospitalException(201, "生成二维码失败");
        }
    }

    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            //根据orderID获取订单信息
            OrderInfo orderInfo = orderService.getById(orderId);
            //封装提交参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //发送httpclient请求，传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //得到微信接口返回数据
            String xml = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            System.out.println("支付状态" + map);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean refund(Long orderId) {
        try {
            //获取支付记录
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //添加信息到退款表
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            //判断订单是否已经退款
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            //调用微信进行退款
            //封装提交参数
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
//       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
//       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);
            //设置调用接口内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            //设置证书
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            //得到微信接口返回数据
            String xml = client.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            if (map != null && WXPayConstants.SUCCESS.equalsIgnoreCase(map.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(map.get(map.get("refund_id")));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(map));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
